<template>
	<div class="system-role-dialog-container">
		<el-dialog :title="state.dialog.title" center class="borderRadius10" v-model="state.dialog.isShowDialog" width="490">
            <el-form ref="roleDialogFormRef" :rules="rules" :model="seckillForm" label-width="120px">
                <el-form-item label="秒杀名称：" prop="seckillManagerName">
                    <el-input class="width420" v-model="seckillForm.seckillManagerName" placeholder="请输入分类名称" />
                </el-form-item>
                <!-- width260 -->
                <el-form-item label="时间范围：">
                    <section class="width420" style="display: flex; justify-content: space-between;">
                        <el-time-picker
                            v-model="state.seckillManagerTimeArr"
                            is-range
                            range-separator="至"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            value-format="HH:mm"
                            format="HH:mm"
                            />
                    </section>
                </el-form-item>
                <el-form-item label="轮播图：">
                    <section class="flex">
                        <el-image v-for="(item, index) in seckillForm.seckillManagerSilderImgs" :key="index" class="mr20"
                            style="width:64px; height: 64px;border-radius: 5px;" :src="item" fit="cover" />
                        <section class="selector-img" @click="addImg('seckillManagerSilderImgs', 1)">
                            <el-icon size="30" color="#999">
                                <Plus />
                            </el-icon>
                        </section>
                    </section>
                </el-form-item>
                <el-form-item label="状态：" style="margin-top: -7px;">
                    <el-switch v-model="seckillForm.seckillManagerStatus" :active-value="1" :inactive-value="0" />
                </el-form-item>
            </el-form>
            <el-row justify="center" class="mt20">
                <el-button @click="closeDialog">取消</el-button>
                <el-button type="primary" @click="onSubmitForm(roleDialogFormRef)">确定</el-button>
            </el-row>
		</el-dialog>
        <AddInformation ref="addInformationRef" @selectFun="selectFun" />
	</div>
</template>

<script setup lang="ts">
import { reactive, ref, defineAsyncComponent } from 'vue';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { seckillAdd, seckillEdite } from "/@/api/marketing";
const AddInformation = defineAsyncComponent(() => import('/@/components/information/AddInformation.vue'))
// 定义变量内容
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
const props = defineProps(['editeItem']);
const roleDialogFormRef = ref<FormInstance>()
const addInformationRef = ref();
const state = reactive({
    loading: false,
    addFileType: '',
    dialog: {
        isShowDialog: false,
        type: 'add',
        title: '',
        submitTxt: '',
    },
    seckillManagerTimeArr:[],
    // 商品分类list
    productCategoryList: [] as Array<any>,
})

//添加入参的接口
interface RuleFormType {
    seckillManagerName: string
    seckillManagerTime: string
    seckillManagerSilderImgs: string[]
    seckillManagerStatus: number
}
//定义添加编辑弹窗参数
const seckillForm = reactive<RuleFormType>({
    seckillManagerName:'',
    seckillManagerTime:'',
    seckillManagerSilderImgs: [],
    seckillManagerStatus: 0,
})
const rules = reactive({
    seckillManagerName: [
    { required: true, message: '请填写秒杀名称…', trigger: 'change' },
  ],
  seckillManagerSilderImgs: [
    { required: true, message: '请添加轮播图…', trigger: 'change',},
  ]
})


// 重置表单
const resetForm = () => {
    roleDialogFormRef.value?.resetFields();
}


// 打开弹窗
const openDialog = (type: string) => {
    state.dialog.type = type;
    resetForm();
    if (type === 'edit') {
        state.dialog.title = '编辑';
        state.dialog.submitTxt = '修 改';
        state.seckillManagerTimeArr = props.editeItem.seckillManagerTime.split(',')
        Object.assign(seckillForm,{
            seckillManagerName:props.editeItem.seckillManagerName,
            seckillManagerSilderImgs: [...props.editeItem.seckillManagerSilderImgs],
            seckillManagerStatus: props.editeItem.seckillManagerStatus,
        })
    } else {
        state.dialog.title = '新增';
        state.dialog.submitTxt = '新 增';
    }
    
    state.dialog.isShowDialog = true;
};
//关闭弹窗
const closeDialog = () => {
    state.dialog.isShowDialog = false;
}

const onSubmitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validate((valid: boolean) => {
        if (valid) {
            state.loading = true;
            let params = JSON.parse(JSON.stringify(seckillForm));
            if (state.dialog.type == 'edit') {//编辑
                params = Object.assign(params,{
                    seckillManagerTime:state.seckillManagerTimeArr?.join(','),
                    seckillManagerId:props.editeItem.seckillManagerId
                });
                seckillEdite(params).then((res:any) =>{//编辑
                    const { code, message } = res;
                    state.loading = false;//loading 关闭
                    closeDialog();//关闭弹窗
                    if(code == 400){
                        ElMessage.success('修改成功');
                        emit('refresh');
                    }
                }).catch(err => {
                    state.loading = false;
                    closeDialog();//关闭弹窗
                });
            } else {
                params = Object.assign(params,{
                    seckillManagerTime:state.seckillManagerTimeArr?.join(','),
                });
                seckillAdd(params).then((res:any) =>{//添加
                    const { code, message } = res;
                    state.loading = false;
                    closeDialog();//关闭弹窗
                    if(code == 400){
                        ElMessage.success('新增成功');
                        emit('refresh');
                    }
                }).catch(err => {
                    state.loading = false;
                    closeDialog();//关闭弹窗
                    ElMessage.info(err);
                });
            }
            return;
            
        } else {
            return false;
        }
        closeDialog();
    });
};

// 图片选中
const addImg = (type: string, isArr: Number) => {
    state.addFileType = type;
    addInformationRef.value.openDialog(isArr)
}

// 图片选中回调
const selectFun = (fileList: any) => {
    if (state.addFileType == 'seckillManagerSilderImgs') {
        seckillForm.seckillManagerSilderImgs = fileList.slice();
    }
}

// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style lang='scss' scoped>
.selector-img {
    width: 64px;
    height: 64px;
    border: 1px solid #ededed;
    border-radius: 5px;
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;

    &:hover {
        background-color: #f5f5f5;
        border: 1px solid #e4e3e3;
    }
}
.width420{
    width: 420px;
}
</style>